package org.mappland.compltres.controller.admin;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.mappland.compltres.common.CommonResult;
import org.mappland.compltres.common.StatusCode;
import org.mappland.compltres.domain.Admin;
import org.mappland.compltres.dto.AdminLoginDTO;
import org.mappland.compltres.service.AdminService;
import org.mappland.compltres.util.WebUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController("adminAdminController")
@RequestMapping("/admin")
public class AdminController {
    @Resource
    private AdminService adminService;

    @PostMapping(value = "/login")
    public CommonResult<Admin> login(@RequestBody AdminLoginDTO loginDTO) {
        CommonResult<Admin> commonResult = new CommonResult<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("admin_name", loginDTO.getUserName());
        String md5password = SecureUtil.md5(loginDTO.getPassword());
        queryWrapper.eq("password", md5password);
        Admin admin = adminService.getOne(queryWrapper);

        if (null != admin) {
            admin.setAdminName(loginDTO.getUserName());
            WebUtils.getSession().setAttribute("loginAdmin", admin);

            commonResult.setCode(StatusCode.COMMON_SUCCESS.getCode());
            commonResult.setMessage(StatusCode.COMMON_SUCCESS.getMessage());
            commonResult.setData(admin);
        } else {
            commonResult.setCode(StatusCode.COMMON_FAIL.getCode());
            commonResult.setMessage(StatusCode.COMMON_FAIL.getMessage());
            commonResult.setData(null);
        }
        return commonResult;

    }

    @GetMapping("/logout")
    public CommonResult<String> logout() {
        CommonResult<String> commonResult = new CommonResult<>();
        WebUtils.getSession().removeAttribute("loginAdmin");

        commonResult.setCode(StatusCode.COMMON_SUCCESS.getCode());
        commonResult.setMessage(StatusCode.COMMON_SUCCESS.getMessage());
        commonResult.setData("退出成功");

        return commonResult;
    }
}
